
import { createSlice } from '@reduxjs/toolkit'
import axios from 'axios'
axios.defaults.baseURL = 'http://localhost:3004/'

const foodsStore = createSlice({
  name: 'foods',
  initialState: {
    cartList: [], // 用来存储购物车的商品
    foodsList: [],
    activeIndex: 0 // 激活的索引
  },
  reducers: {
    // 清空购物车
    clearCartList(state) {
      state.cartList = []
    },
    // 递增
    increment(state, action) {
      const item = state.cartList.find(v => v.id === action.payload)
      item.count++
    },
    // 递减
    decrement(state, action) {
      const item = state.cartList.find(v => v.id === action.payload)
      item.count--
      // 先--，-完后再判断，如果为0，则删除该商品
      if (item.count === 0) {
        state.cartList = state.cartList.filter(v => v.id !== item.id)
      }
    },
    addCartList(state, action) {
      // 判断是否已经存在，如果存在，数量+1，否则，直接push

      const { id } = action.payload

      const foods = state.cartList.find(v => v.id === id)

      if (foods) {
        foods.count++
      } else {
        state.cartList.push(action.payload)
      }

    },
    setActiveIndex(state, action) {
      state.activeIndex = action.payload
    },
    setFoodsList(state, action) {
      state.foodsList = action.payload
    }
  }
})

export const foodsActions = {

  ...foodsStore.actions,

  getFoodsList() {
    return async (dispatch) => {
      const res = await axios({
        method: 'GET',
        url: '/takeaway'
      })
      dispatch(foodsStore.actions.setFoodsList(res.data))
    }
  }
}


export default foodsStore.reducer